<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author:  Zl
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\User;
use app\common\traits\ActionRecordTrait;
use think\facade\Db;
use app\admin\model\Common;
use think\response\Json;
use think\Validate;
use app\crm\logic\WhereLogic;

use app\admin\controller\ApiCommon;
use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;


class MiniProgramModel extends Common
{
    use ActionRecordTrait;
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer';


    // 【小程序】服务评价列表
    public function getEvaluationList($request): array
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;

        $score_array = [
            '1' => '0',
            '2' => '40',
            '3' => '60',
            '4' => '80',
            '5' => '100',
        ];

        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];

        // 查询时间 
        $create_time_start = $request['create_time_start'] ?? '';
        $create_time_end   = $request['create_time_end'] ?? '';

        if($create_time_start){

            $create_time_starts = strtotime($create_time_start);

            array_push($where,['create_time','>=',$create_time_starts]);

        }

        if($create_time_end){

            $create_time_ends = strtotime($create_time_end.' 23:59:59');

            array_push($where,['create_time','<=',$create_time_ends]);
            
        }

        // 查询门店
        $shop_id = $request['shop_id'] ?? '';

        if($shop_id){

            array_push($where,['shop_id','=',$shop_id]);

        }

        $score_type = $request['score_type'] ?? '';

        if($score_type){

            array_push($where,['score_amount','=',$score_array[$score_type]]);

        }

        // 是否月度首次评价
        $is_first = $request['is_first'] ?? '';

        if($is_first){

            array_push($where,['score_one|score_two|score_three|score_four','>','0']);

        }

        $wenjuan = $request['wenjuan'] ?? '1';

        array_push($where,['wenjuan','=',$wenjuan]);

        $is_export = $request['is_export'] ?? '';

        if($is_export == '0'){

            $orderby = 'id DESC';

            $dataCount = Db::name('service_log_evaluation')->where($where)->count();

            $list = Db::name('service_log_evaluation')
                    ->where($where)
                    ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                    ->order($orderby)
                    ->select()->toArray();

        }

        if($is_export == '1'){

            $list = Db::name('service_log_evaluation')->where($where)->select()->toArray();

        }
        
        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        $customer_ids = array_values(array_unique(array_column($list, 'customer_id')));

        $servicelog_ids = array_values(array_unique(array_column($list, 'servicelog_id')));

        $shop_ids = array_values(array_unique(array_column($list, 'shop_id')));

        // 评价客户id
        $where = [];

        array_push($where,['id','in',$customer_ids]);

        $customer_names = Db::name('customer')->where($where)->column('customer_name,telephone','id');

        // 评价服务id
        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shop_names = Db::name('shop')->where($where)->column('shop_name','shop_id');

        $show = [];
        foreach ($list as $key => $value) {
            
            $one = [];

            $one['id'] = $value['id'];

            $one['customer_name'] = $customer_names[$value['customer_id']]['customer_name'] ?? '';

            $one['tel'] = $customer_names[$value['customer_id']]['telephone'] ?? '';

            $one['shop_name'] = $shop_names[$value['shop_id']] ?? '';
        
            $one['score_amount'] = $value['score_amount'];

            if($value['score_one']){
                $one['score_one'] = $value['score_one'] == 1 ? '是' : '否';
            }else{
                $one['score_one'] = "";
            }

            if($value['score_two']){
                $one['score_two'] = $value['score_two'] == 1 ? '是' : '否';
            }else{
                $one['score_two'] = "";
            }

            if($value['score_three']){
                $one['score_three'] = $value['score_three'] == 1 ? '是' : '否';
            }else{
                $one['score_three'] = "";
            }

            if($value['score_four']){
                $one['score_four'] = $value['score_four'] == 1 ? '是' : '否';
            }else{
                $one['score_four'] = "";
            }

            if($value['score_five']){
                $one['score_five'] = $value['score_five'] == 1 ? '是' : '否';
            }else{
                $one['score_five'] = "";
            }
            
            $one['rate_text'] = $value['rate_text'];

            $one['create_time'] = $value['create_time'] > 0 ? date('Y-m-d H:i:m',$value['create_time']) : '';

            array_push($show,$one);

        }

        $data = [];

        $data['list'] = $show ?? [];

        $data['dataCount'] = $dataCount ?? '0';

        return $data;
    }

    // 【小程序】意见反馈列表
    public function getFeedbackList($request): array
    {

        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];

        // 查询时间 
        $create_time_start = $request['create_time_start'] ?? '';
        $create_time_end   = $request['create_time_end'] ?? '';

        if($create_time_start){

            $create_time_starts = strtotime($create_time_start);

            array_push($where,['create_time','>=',$create_time_starts]);

        }

        if($create_time_end){

            $create_time_ends = strtotime($create_time_end.' 23:59:59');

            array_push($where,['create_time','<=',$create_time_ends]);
            
        }

        // 查询门店
        $shop_id = $request['shop_id'] ?? '';

        if($shop_id){

            array_push($where,['shop_id','=',$shop_id]);

        }

        $score_type = $request['feed_type'] ?? '';

        if($score_type){

            array_push($where,['type','=',$score_type]);

        }

        $is_export = $request['is_export'] ?? '';

        if($is_export == '0'){

            $orderby = 'id DESC';

            $dataCount = Db::name('feedbacks')->where($where)->count();
    
            $feedbackList = Db::name('feedbacks')->where($where)->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->order($orderby)->select()->toArray();    

        }

        if($is_export == '1'){

            $feedbackList = Db::name('feedbacks')->where($where)->select()->toArray();    

        }
        
        
        $customer_ids = array_values(array_unique(array_column($feedbackList, 'customer_id')));

        $shop_ids = array_values(array_unique(array_column($feedbackList, 'shop_id')));

        $feed_type_ids = array_values(array_unique(array_column($feedbackList, 'type')));

        // 客户信息
        $where = [];

        array_push($where,['id','in',$customer_ids]);

        $customer_info = Db::name('customer')->where($where)->column('customer_name,telephone','id');


        // 门店信息
        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shop_names = Db::name('shop')->where($where)->column('shop_name','shop_id');


        // 分类
        $where = [];

        array_push($where,['id','in',$feed_type_ids]);

        $feed_types = Db::name('setting')->where($where)->column('name','id');

        $list = [];

        foreach ($feedbackList as $key => $value) {
            
            $one = [];

            $one['id'] = $value['id'] ?? '';

            $one['customer_name'] = $customer_info[$value['customer_id']]['customer_name'] ?? '';

            $one['tel'] = $customer_info[$value['customer_id']]['telephone'] ?? '';

            $one['shop_name'] = $shop_names[$value['shop_id']] ?? '';

            $one['type'] = $feed_types[$value['type']] ?? '';

            $one['feed_back_value'] = $value['feed_back_value'] ?? '';

            $one['create_time'] = $value['create_time'] > 0 ? date('Y-m-d H:i:m',$value['create_time']) : '';

            array_push($list,$one);

        }



        $data = [];

        $data['list'] = $list ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        return $data;
    }

    public function getAnswers($request): array
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";exit;

        $wenjuanID = $request['wenjuanID'] ?? '2';

        $where = [];

        array_push($where,['id','=',$wenjuanID]);

        $questionStr = Db::name('questionnaire')->where($where)->value('qusetion_ids');

        $questionIds = explode(',',$questionStr);

        $where = [];

        array_push($where,['id','in',$questionIds]);

        $questionTitles = Db::name('question')->where($where)->column('id,question_describe');

        $data = [];

        $data['list'] = $questionTitles ?? [];

        return $data;
        
    }

    public function getManyiduList($request): array
    {

        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";
        // exit;
        
        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;

        $where = [];

        // 查询时间 
        $create_time_start = $request['create_time_start'] ?? '';
        $create_time_end   = $request['create_time_end'] ?? '';

        if($create_time_start){

            $create_time_starts = strtotime($create_time_start);

            array_push($where,['create_time','>=',$create_time_starts]);

        }

        if($create_time_end){

            $create_time_ends = strtotime($create_time_end.' 23:59:59');

            array_push($where,['create_time','<=',$create_time_ends]);
            
        }

        // 查询门店
        $shop_id = $request['shop_id'] ?? '';

        if($shop_id){

            array_push($where,['shop_id','=',$shop_id]);

        }

        $question_ids = $request['wenjuanID'] ?? '';

        array_push($where,['questionnaire_id','=',$question_ids]);

        $is_export = $request['is_export'] ?? '';

        $orderby = 'id DESC';

        if($is_export == '0'){

            $dataCount = Db::name('question_customer')->where($where)->count();

            // mainSql-------------------------------
            $question_csutomers = Db::name('question_customer')->where($where)->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->order($orderby)->select()->toArray();

        }else{

            // mainSql-------------------------------
            $question_csutomers = Db::name('question_customer')->where($where)->order($orderby)->select()->toArray();

        }

        // echo "<pre>";
        // print_r($where);
        // echo "</pre>";

        // echo "<pre>";
        // print_r($question_csutomers);
        // echo "</pre>";
        // exit;

        $where = [];

        array_push($where,['id','=',$question_ids]);

        $wenjuanInfo = Db::name('questionnaire')->where($where)->value('qusetion_ids');

        $questionIds = explode(',',$wenjuanInfo);

        $where = [];

        array_push($where,['id','in',$questionIds]);

        $question_answers = Db::name('question_answer')->where($where)->column('describe,score','id');

        // echo "<pre>";
        // print_r($question_answers);
        // echo "</pre>";
        // exit;

        $customer_ids = array_values(array_unique(array_column($question_csutomers, 'customer_id')));

        $shop_ids = array_values(array_unique(array_column($question_csutomers, 'shop_id')));

        // 客户信息
        $where = [];

        array_push($where,['id','in',$customer_ids]);

        $customer_info = Db::name('customer')->where($where)->column('customer_name,telephone','id');
 
 
        // 门店信息
        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shop_names = Db::name('shop')->where($where)->column('shop_name','shop_id');



        $list = [];

        $callName = [];

        foreach ($question_csutomers as $key => $value) {

            $one = [];

            $one['id'] = $value['id'] ?? '';

            $one['customer_id'] = $customer_info[$value['customer_id']]['customer_name'] ?? '';

            $one['telephone'] = $customer_info[$value['customer_id']]['telephone'] ?? '';

            $one['shop_id'] = $shop_names[$value['shop_id']] ?? '';

            // 数据表头信息---------------------------------------------------------start
            if($key == '0'){

                $callName['customer_id'] = '顾客姓名';

                $callName['telephone'] = '手机号';
    
                $callName['shop_id'] = '门店';

            }
            
            // 数据表头信息---------------------------------------------------------end

            $score = explode(',',$value['answers']);

            $scoreAmount = 0;

            foreach ($questionIds as $k => $v) {
                
                $question_answers = Db::name('question')->where('id',$v)->value('question_answer');

                if($question_answers){

                    $answerIds = explode(',',$question_answers);
    
                    $where = [];
    
                    if($score[$k] > 0){

                        array_push($where,['id','=',$answerIds[$score[$k]-1]]);
    
                        $answer = Db::name('question_answer')->where($where)->value('describe');

                        $scoreAmount = bcadd($scoreAmount,$score[$k],0);
                        
                    }
                    
    
                }else{

                    $answer = $score[$k] ?? '';

                }

                $one[$v] = $answer ?? '';

                

                if($key == '0'){

                    $question_describe = Db::name('question')->where('id',$v)->value('question_describe');

                    $callName[$v] = $question_describe;

                }
                

            }

            $one['scoreAmount'] = $scoreAmount ?? '0';

            $one['create_time'] = $value['create_time'] > 0 ? date('Y-m-d H:i:m',$value['create_time']) : '';

            if($key == '0'){

                $callName['scoreAmount'] = '总分';

                $callName['create_time'] = '时间';
                
            }

            // exit;
            // echo "<pre>";
            // print_r($score);
            // echo "</pre>";
            // exit;

            array_push($list,$one);

        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";
        // exit;

        $data = [];

        $data['list'] = $list ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        $data['callName'] = $callName ?? [];

        return $data;
        
    }

    public function getBannerList($request)
    {
        // 分页数据
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 10;

        $dataCount = Db::name('mini_banner')->count();

        $list = Db::name('mini_banner')->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])->order('id DESC')->select()->toArray();

        $data = [];

        $data['list'] = $list ?? [];

        $data['dataCount'] = $dataCount ?? 0;

        return $data;
    }

    public function addBanner($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        $url = $request['uploadList'][0] ?? '';

        if(!$url){
            return ['error' => '请选择图片！','id' => ''];
        }

        // $p = Db::name('mini_banner')->where('url',$url)->find();

        // if($p){
        //     return ['error' => '请勿重复添加！'];
        // }

        $data = [
            'title'       => $request['title'] ?? '',
            'target_url'  => $request['target_url'] ?? '',
            'start_time'  => $request['start_time'] ? strtotime($request['start_time']) : '',
            'over_time'   => $request['over_time'] ? strtotime($request['over_time']) : '',
            'use_status'  => 0,
            'create_time' => time(),
            'url'         => $request['uploadList'][0],
        ];

        $id = Db::name('mini_banner')->insertGetId($data);

        return ['error' => '添加成功！','id'=>$id];

    }

    public function changBannerStatus($request)
    {
        // echo "<pre>";
        // print_r($request);
        // echo "</pre>";

        Db::name('mini_banner')->where('id',$request['id'])->update(['use_status' => $request['status_type']]);

        return ['error' => '修改成功！','id' => ''];
    }

}